package cn.btks.backstagemanage.role.repository;

import cn.btks.backstagemanage.menu.repository.MenuRepository;
import cn.btks.commonserver.util.sm2.SM2EncDecUtils;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author lijun
 * @Date 2021/1/21 18:05
 */
@Repository
public class RoleBaseRepository {
    @Autowired
    MenuRepository menuRepository;

    @Autowired
    JdbcTemplate jdbcTemplate;

    /**
     * 根据资源清单ID删除关联自身及子资源清单
     * @param roleId
     * @param menuIdList
     */
    public void deleteMenuRoles(Long roleId, List<Long> menuIdList){
        String sql = "delete from menu_roles where roles_id = ? and menu_id = ?";
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
                Long menuId = menuIdList.get(i);
                preparedStatement.setLong(1, roleId);
                preparedStatement.setLong(2, menuId);
            }

            @Override
            public int getBatchSize() {
                return menuIdList.size();
            }
        });
    }

    /**
     * 根据资源清单ID删除关联自身及子资源清单（加密）
     * @param roleId
     * @param menuIdList
     */
    public void deleteMenuRoles1(Long roleId, List<Long> menuIdList){
        String sql = "delete from menu_roles where roles_id = ? and menu_id = ?";
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @SneakyThrows
            @Override
            public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
                Long menuId = menuIdList.get(i);
                preparedStatement.setString(1, SM2EncDecUtils.encrypt(String.valueOf(roleId)));
                preparedStatement.setString(2, SM2EncDecUtils.encrypt(String.valueOf(menuId)));
            }

            @Override
            public int getBatchSize() {
                return menuIdList.size();
            }
        });
    }
}
